package com.student.web.admin;

import com.student.pojo.Admin;
import com.student.service.admin.AdminService;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
 * get/post 参数code username password
 * 返回JavaScript
 * @author lin945
 * @date 2020/4/25 13:46
 */
@WebServlet("/LoginServlet")
public class adminServlet extends HttpServlet {
    private AdminService adminService=new AdminService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-type","text/html;charset=UTF-8");
        HttpSession session = req.getSession();
        if (session.getAttribute("username") != null) {
            resp.sendRedirect(req.getContextPath() + "/home");
            return;
        }
        String code = req.getParameter("code");
        if (!code.equals(session.getAttribute("code"))) {
            resp.getWriter().write("<script language='JavaScript'>alert('您的验证码有误，请重新输入或者注册');window.location.href='"+req.getContextPath()+"/login'</script>");
            return;
        }
        Admin admin=new Admin();
        Map<String, String[]> parameterMap = req.getParameterMap();
        try {
            BeanUtils.populate(admin,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
       if (adminService.login(admin)!=null){
           session.setAttribute("username",admin.getUsername());
           session.setMaxInactiveInterval(7 * 24 * 3600);
           // Session保存7天
           Cookie cookie = new Cookie("admin", session.getId());
           cookie.setMaxAge(7 * 24 * 3600);
           // cookie的有效期也为7天
           cookie.setPath("/");
           resp.addCookie(cookie);
           resp.getWriter().write("<script language='JavaScript'>alert('登录成功');window.location.href='"+req.getContextPath()+"/home'</script>");
       }else {
           resp.getWriter().write("<script language='JavaScript'>alert('您的用户名或密码有误，请重新输入或者注册');window.location.href='"+req.getContextPath()+"/login'</script>");
       }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
